package com.j2ee.method.invocation;

import java.util.HashMap;
import java.util.Map;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;

public class StatisticsMethodCount {
	
	private Map<String, StatisticsClass> classmap = new HashMap<String, StatisticsClass>() ;
	
	public Map<String, StatisticsClass> getClassmap() {
		return classmap;
	}
	
	/**
	 * 前置通知——统计dao、service、dao层中所有类的方法的调用次数
	 * @param joinPoint
	 */
	public void statisticsInvocationCount(JoinPoint joinPoint) {
		/**
		 * 先判断map中有没有 该类的方法，如果有，计算器+1；如果没有，计算器初始化为1
		 */
		String classname = joinPoint.getTarget().getClass().getName() ;
		String methodname = joinPoint.getSignature().getName() ;
		//map用法实例
		String key = classname + ":" + methodname ;
		if(classmap.containsKey(key)) {
			StatisticsClass statisticsClass = classmap.get(key) ;
			statisticsClass.setCount(statisticsClass.getCount() + 1) ;
		} else {
			StatisticsClass statisticsClass = new StatisticsClass() ;
			statisticsClass.setClassname(classname) ;
			statisticsClass.setMethodname(methodname) ;
			statisticsClass.setCount(1) ;
			classmap.put(key, statisticsClass) ;
		}
	}
	
	/**
	 * 环绕通知——计算action层中类的方法的调用时间
	 * @throws Throwable 
	 */
	public void statisticsActionMethodInvocationTime(ProceedingJoinPoint joinPoint) throws Throwable {
		
		float begin = System.currentTimeMillis() ;
		joinPoint.proceed() ;
		float end = System.currentTimeMillis() ;
		float executionTime = (end - begin)  ;
		
		/**
		 * 先判断map中有没有该方法，如果有，调用时间后继续追加；如果没有，添加调用时间
		 */
		String classname = joinPoint.getTarget().getClass().getName() ;
		String methodname = joinPoint.getSignature().getName() ;
		String key = classname + ":" + methodname ;
		if(classmap.containsKey(key)) {
			StatisticsClass statisticsClass = classmap.get(key) ;
			statisticsClass.setCount(statisticsClass.getCount() + 1) ;
			statisticsClass.setExecutionTime("," + executionTime) ;
		} else {
			StatisticsClass statisticsClass = new StatisticsClass() ;
			statisticsClass.setClassname(classname) ;
			statisticsClass.setMethodname(methodname) ;
			statisticsClass.setCount(1) ;
			statisticsClass.setExecutionTime(executionTime + "") ;
		}
	}

}
